<?php
/**
 * 《网络信息》实现类
 *
 * @author 孙晓晔
 * @version $Id: Mac.class.php 1061 2010-04-09 08:31:55Z sunxy $
 */
require_once(dirname(__FILE__) . '/EmpUtil.class.php');

class Mac extends EmpUtil {
	public $tbl = Constant::tbl_emp_mac;

	public $dhcp = array(
		'-' => '请选择',
		'1' => '是',
		'2' => '否',
	);
	
	public $internet = array(
		'-' => '请选择',
		'1' => '是',
		'2' => '否',
	
		'9' => '其它',
	);

	public $category = array(
		'-' => '请选择',
		'1' => '电脑',		
		'2' => '语音网关',
		'3' => '服务器',
		'4' => '路由器',
		'5' => '手机',
		'6' => '摄像头',
		'7' => '打印机',
		'8' => '注塑机',
		'10' => '机器设备',
	
		'9' => '其它',
	);

	public $status = array(
		'-' => '请选择',
		'1' => '联机',
		'2' => '脱机',
	
		'9' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'office' => '办公区',
		'dept' => '部门',
		'emp' => '员工',
		'mac' => 'mac',
		'ip' => 'ip',
	
		'upload' => '上传',
		'download' => '下载',
	
		'1' => '创建时间',
		'2' => '更新时间',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);

		$controller->assign_by_ref('category_option', $this->category);
		$controller->assign_by_ref('dhcp_option', $this->dhcp);

		$controller->assign_by_ref('internet_option', $this->internet);
	}
	
	function tab($controller, $request) {		
		$data = array(
			'ARP信息' => array('cc'=>'log.php?do=Arp.find', 'js'=>'1'),
			'网络流量' => array('cc'=>'log.php?do=Network.find', 'js'=>'1'),
			'上网日志' => array('cc'=>'log.php?do=Layer7.find', 'js'=>''),
			'电脑开机' => array('cc'=>'log.php?do=ArpLog.find', 'js'=>''),
			'IP分配' => array('cc'=>'emp.php?do=Mac.find', 'js'=>'1'),

			// '内网地址' => array('cc'=>'info.php?do=Ip.find', 'js'=>''),
		);
		
		$ret = $this->_tab($data);

		$controller->assign_by_ref('result', $ret);

		$controller->display($request, 'tab');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		$controller->display($request, 'emp/mac/find');
		return true;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}
	
		$emp = $_SESSION['id'];
	
		$p = array('1'=>'206', '2'=>'207', '3'=>'208');
	
		$a = $this->_audit_office($p);
		if (count($a) > 0) {
			$office = implode(",", $a);
	
			return sprintf(" visible = 1 AND (office in (%s) OR oper = '%s')", $office, $emp);
		}
	
		return sprintf(" visible = 1 AND (emp = '%s' OR oper = '%s')", $emp, $emp);
	}
	
	function _where($request) {		
		$category_s = $request['category_s'];
		$internet_s = $request['internet_s'];

		$mac_s = str_replace("-", ":", $request['mac_s']);
		$ip_s = $request['ip_s'];
		$gw_s = $request['gw_s'];

		$dhcp_s = $request['dhcp_s'];
		
		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}

		if (!empty($category_s) && $category_s <> '-') {
			$where .= " AND `category` = '" . $category_s . "'";
		}
		
		if (!empty($internet_s) && $internet_s <> '-') {
			$where .= " AND `internet` = '" . $internet_s . "'";
		}

		if (!empty($mac_s)) {
			$where .= " AND mac = '" . $mac_s . "'";
		}

		if (!empty($ip_s)) {
			$where .= " AND ip like '" . $ip_s . "%'";
		}

		if (!empty($gw_s)) {
			$where .= " AND gw = '" . $gw_s . "'";
		}

		if (!empty($dhcp_s) && $dhcp_s <> '-') {
			$where .= " AND `dhcp` = '" . $dhcp_s . "'";
		}
		
		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);
		
		return $where;
	}
	
	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'emp/mac/list');
		return true;
	}
	
	function view($controller, $request) {
		$this->pretreat($controller);

		if (!empty($request['id'])) {
			$row = $this->_view($request['id']);
		} elseif (!empty($request['ip'])) {
			$row = $this->_view_ip($request['ip']);
		} elseif (!empty($request['mac'])) {
			$row = $this->_view_mac($request['mac']);
		}

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'emp/mac/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
				
		$row['category_t'] = $this->category[$row['category']];
		$row['internet_t'] = $this->internet[$row['internet']];
		$row['dhcp_t'] = $this->dhcp[$row['dhcp']];
		
		$row = $this->_view_t($row);

		return $row;
	}
	
	function _view_ip($ip) {		
		$row = Common::x($this->tbl, 'ip', $ip);
		if (!$row) {
			return false;
		}
		
		$row = $this->_view(null, $row);

		return $row;
	}
	
	function _mac_ip($ip) {
		$row = Common::x($this->tbl, "ip", $ip);
		if (!$row) {
			return false;
		}
		
		$row = $this->_view(null, $row);
		
		return $row;
	}
	
	function _view_mac($mac) {		
		$row = Common::x($this->tbl, 'mac', $mac);
		if (!$row) {
			return false;
		}
				
		$row = $this->_view(null, $row);

		return $row;
	}
	
	function qr($controller, $request) {
		$this->pretreat($controller);
	
		$row = $this->_view($request['id']);
		
		if (empty($row['content'])) {
			return false;
		}
	
		global $cfg;
	
		$errorCorrectionLevel = 'M';
		$matrixPointSize = '5';
		
		$filename = sprintf("%s%s%s_mac_%s_%s_%s.png", $cfg['upload'], '/qrcode/', $row['id'], $errorCorrectionLevel, $matrixPointSize, strtotime($row['modifytime']));
		debug($filename);
		if (file_exists($filename)) {
			debug("exist.");
			return $this->_png($filename);
		}
	
		debug("new png.");
	
		$s = $row['content'];
	
		require_once(APP_LIB . 'phpqrcode/qrlib.php');
	
		// return QRcode::png($s, false, $errorCorrectionLevel, $matrixPointSize);
		QRcode::png($s, $filename, $errorCorrectionLevel, $matrixPointSize);
	
		return $this->_png($filename);
	}
	
	function _png($filename) {
		Header("Content-type: image/png");
		$im = imageCreateFromPng($filename);
		imagePng($im);
		ImageDestroy($im);
	
		return $im;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function copy($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'emp/mac/copy');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function copyPost($controller, $request) {
		return $this->addPost($controller, $request);
	}
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->display($request, 'emp/mac/add');
		return true;
	}

	function gw($office) {
		if ($office == '2') {
			return $this->gw_sj;
		}

		return $this->gw_ns;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$emp = $request['id'];
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$dhcp = $request['dhcp'];
		$category = $request['category'];

		$mac = $request['mac'];
		$ip = $request['ip'];
		$netmask = $request['netmask'];
		$gw = $request['gw'];

		// $orderby = $this->xxx($ip);
		$content = $request['content'];

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(office, dept, emp, category, dhcp, mac, ip, netmask, gw, content, oper, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $office, $dept, $emp, $category, $dhcp, $mac, $ip, $netmask, $gw, $content, $_SESSION['id']);
		// debug($sql);
		$db->query($sql);
		
		$request['id_s'] = $db->insert_id();
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'emp/mac/edit');
		return true;
	}

	function _ip($ip) {
		require_once(dirname(__FILE__) . '/../info/Ip.class.php');
		$aa = new Ip();
		
		return $aa->_ip($ip);
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$name = addslashes($request['name']);
		$ip1 = $request['ip1'];
		$ip = $request['ip'];
		$ip = $this->_input($request['ip']);
		
		$mac = trim($request['mac']);

		// $this->_update_ip($ip1, $ip2);
		$dhcp = $request['dhcp'];
		$category = $request['category'];
		$internet = $request['internet'];
		
		$username = addslashes($request['username']);
		$password = addslashes($request['password']);
		
		$netmask = $request['netmask'];
		$gw = $request['gw'];
		$dns = $request['dns'];
		
		$upload = trim($request['upload']);
		$download = trim($request['download']);

		// $orderby = $this->xxx($ip2);
		
		$content = $request['content'];		
		$status = $request['status'];

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET office = '%s', dept = '%s', emp = '%s', name = '%s', mac = '%s', category = '%s', internet = '%s', dhcp = '%s', ip = '%s', netmask = '%s',";
		$fmt .= " gw = '%s', dns = '%s', `upload` = '%s', `download` = '%s', username = '%s', password = '%s', content = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $office, $dept, $emp, $name, $mac, $category, $internet, $dhcp, $ip, $netmask, $gw, $dns, $upload, $download, $username, $password, $content, $status, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _update_ip($ip1, $ip2) {
		require_once(dirname(__FILE__) . '/../info/Ip.class.php');
		$aa = new Ip();
		
		$aa->_update2($ip1, $ip2);
	}
	
	function _add($request) {
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		
		$mac = $request['mac'];
		$ip = $request['ip'];
		$netmask = $request['netmask'];
		$gw = $request['gw'];

		// $orderby = $this->xxx($ip);
		$content = $request['content'];		

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(emp, mac, ip, netmask, gw, content, oper, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $emp, $mac, $ip, $netmask, $gw, $content, $_SESSION['id']);
		debug($sql);
		$db->query($sql);
		if ($db->affected_rows() > 0) {
			// $fmt = "UPDATE %s SET status = '1', modifytime = now() WHERE ip = '%s'";
			// $sql = sprintf($fmt, Constant::tbl_ip, $ip);
			// debug($sql);
			// $db->query($sql);
		}
	}

	function ajax_arp($controller, $request) {
		$cmd = "/sbin/arp -n";
		// echo $cmd;
		$s = shell_exec($cmd);
		 
		$request['data'] = $s;
			
		return $this->importPost($controller, $request);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function importPost($controller, $request) {
		$this->pretreat($controller);

		$aa = preg_split("/[\\n]+/i", $request['data']);

		require_once APP_LIB . 'IpAddr.class.php';
		$ipaddr = new IpAddr();

		$db = newdb($this->dsn_w);
		while (list($k, $v) = each($aa)) {
			$buf = trim($v);
			if (strlen($buf) < 5) {
				continue;
			}
			$a = preg_split("/[\\s,]+/", $buf);

			if (count($a) < 4) {
				continue;
			}
				
			if (!preg_match("/^(\d+)/", $a[0])) {
				continue;
			}

			$mac = strtoupper($a[2]);
			$ip = $a[0];

			$fmt = "SELECT * FROM %s WHERE mac = '%s'";
			$sql = sprintf($fmt, Constant::tbl_emp_mac, $mac);
			$result = $db->query($sql);
			if ($db->num_rows($result) > 0) {
				continue;
			}

			if ($ipaddr->contains('192.168.2.0/24', $ip)) {
				$gw = "192.168.2.12";
			} else if ($ipaddr->contains('192.168.3.0/24', $ip)) {
				$gw = "192.168.3.12";
			}

			$netmask = "255.255.255.0";
				
			$orderby = $this->xxx($ip);

			$fmt = "INSERT INTO %s(mac, ip, netmask, gw, orderby, createtime, modifytime) VALUES('%s', '%s', '%s', '%s', '%s', now(), now())";
			$sql = sprintf($fmt, Constant::tbl_emp_mac, $mac, $ip, $netmask, $gw, $orderby);
			// debug($sql);
			$result = $db->query($sql);
			if ($db->affected_rows() > 0) {
				$fmt = "UPDATE %s SET status = '1' WHERE ip = '%s'";
				$sql = sprintf($fmt, Constant::tbl_ip, $ip);
				$db->query($sql);
			}
		}
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function ajax_dhcpd_ns($controller, $request) {
		$request['range'] = '192.168.16.0/22';
		echo $this->_dhcpd($controller, $request);
	}

	function ajax_dhcpd_sj($controller, $request) {
		$request['range'] = '192.168.0.0/21';
		echo $this->_dhcpd($controller, $request);
	}
	
	function ajax_dhcpd_qx($controller, $request) {
		$request['range'] = '192.168.8.0/22';
		echo $this->_dhcpd($controller, $request);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function _dhcpd($controller, $request) {
		$request['tpl'] = "html4";

		$range = $request['range'];
		if (empty($range)) {
			$range = "192.168.16.0/22";
		}
		
		require_once APP_LIB . 'IpAddr.class.php';
		$ipaddr = new IpAddr();

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE dhcp = '1' ORDER BY orderby";
		$sql = sprintf($fmt, Constant::tbl_emp_mac);
		// debug($sql);
		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			if ($ipaddr->contains($range, $row['ip'])) {
				$row = $this->_view(null, $row);
				$data[] = $row;
			}
		}

		$controller->assign_by_ref('result', $data);

		if (empty($range) || $range == '192.168.16.0/22') {
			return $controller->sunxy($request, 'emp/mac/ns');
		} elseif ($range == '192.168.8.0/22') {
			return $controller->sunxy($request, 'emp/mac/qx');
		} else {
			return $controller->sunxy($request, 'emp/mac/sj');
		}
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function delete($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}

			$fmt = "SELECT * FROM %s WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $id);
			$result = $db->query($sql);
			if ($row = $db->fetch_array($result)) {
				$fmt = "UPDATE %s SET status = '2', modifytime = now() where ip = '%s'";
				$sql = sprintf($fmt, Constant::tbl_ip, $row['ip']);
				// debug($sql);
				$db->query($sql);
			}

			$fmt = "DELETE FROM %s WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $id);
			// debug($sql);
			$db->query($sql);
		}
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function a($controller, $request) {
		$cmd = "/sbin/iptables -L -n -vx";

		$ret = shell_exec($cmd);

		echo $ret;

		$aa = preg_split("/[\\n]+/i", $ret);
		// print_r($a);

		$rr = array();
		// $db = newdb($this->dsn);
		while (list($k, $v) = each($aa)) {
			$buf = trim($v);
			if (strlen($buf) < 10) {
				continue;
			}

			if (preg_match("/^Chain|pkts/i", $buf)) {
				echo $buf . "\n";
				continue;
			}

			$a = preg_split("/[\t|\s]+/i", $buf);
			// print_r($a);
			if ($a[0] == 0 || $a[7] == '0.0.0.0/0') {
				continue;
			}

			$rr[] = $a;
		}

		usort($rr, 'cmp');
		print_r($rr);

		$controller->assign_by_ref('result', $rr);

		$controller->display($request, 'emp/mac/a');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ajax_exist($controller, $request) {
		$ip = $request['ip_new'];

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE ip = '%s'";
		$sql = sprintf($fmt, $this->tbl, $ip);
		// debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			echo "false";
		} else {
			echo "true";
		}

		return true;
	}

	/**
	 *
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function t($controller, $request) {
		$db = newdb($this->dsn_w);

		$file = "/home/ftp/tecmold.com/mac.txt";
		$file = "d:/mac.txt";
		$fd = fopen($file, "r");
		while (!feof($fd)) {
			$buf = fgets($fd);
			// echo $buf;

			if (strlen($buf) < 5) {
				continue;
			}
			$a = preg_split("/[\\s,]+/", $buf);

			print_r($a);

			$mac = $a[2];
			$ip = $a[0];

			$fmt = "INSERT INTO %s(mac, ip, createtime, modifytime) VALUES('%s', '%s', now(), now())";
			$sql = sprintf($fmt, Constant::tbl_emp_mac, $mac, $ip);
			echo $sql . "\n";
			$db->query($sql);
		}
		fclose($fd);

		echo "\n" . $_REQUEST['do'] . "\n";

		logdate($controller, $request);
		return true;
	}
	
	function ns($controller, $request) {				
		$this->test('192.168.16.0/22');
		
		echo "\n" . $_REQUEST['do'] . "\n";

		logdate($controller, $request);
		return true;
	}
	
	function qx($controller, $request) {
		$this->test('192.168.8.0/22');
	
		echo "\n" . $_REQUEST['do'] . "\n";
	
		logdate($controller, $request);
		return true;
	}
	
	function sj($controller, $request) {		
		$this->test('192.168.0.0/21');
		
		echo "\n" . $_REQUEST['do'] . "\n";

		logdate($controller, $request);
		return true;
	}
	
	function test($range) {
		require_once APP_LIB . 'IpAddr.class.php';
		$ipaddr = new IpAddr();

		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if (!$ipaddr->contains($range, $row['ip'])) {
				continue;
			}
			
			$t1 = time();
			if ($this->ping($row['ip'])) {
				$status = '1';
			} else {
				$status = '2';
			}
			
			$fmt = "UPDATE %s SET status = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $status, $row['id']);
			$db->query($sql);
			
			echo sprintf("%s = %s, time = %s\n", $row['ip'], $status, time() - $t1);
		}
	}
	
	function ns2($controller, $request) {
		$request['a'] = '336';
		$request['range'] = "192.168.16.0/22";
		$request['title'] = '电脑是否开机（南山）';
		
		$this->open($controller, $request);
	}
	
	function qx2($controller, $request) {
		$request['a'] = '353';
		$request['range'] = "192.168.8.0/22";
		$request['title'] = '电脑是否开机（清溪）';
	
		$this->open($controller, $request);
	}
	
	function sj2($controller, $request) {
		$request['a'] = '337';
		$request['range'] = "192.168.0.0/21";
		$request['title'] = '电脑是否开机（沙井）';
		
		$this->open($controller, $request);
	}
	
	function open($controller, $request) {
		$bb = $this->_list_email($request['a']);
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}

		require_once APP_LIB . 'IpAddr.class.php';
		$ipaddr = new IpAddr();

		$range = $request['range'];

		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE category = '1'";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if (!$ipaddr->contains($range, $row['ip'])) {
				continue;
			}
			
			$t1 = time();
			if ($this->ping($row['ip'])) {
				$row = $this->_view(null, $row);
				
				$ret[] = $row;
			}
			
			echo sprintf("%s = %s, time = %s\n", $row['ip'], $row['status'], time() - $t1);
		}
		
		$from = $this->email;
		$subject = $request['title'];
		// print_r($ret);
				
		$controller->assign_by_ref('result', $ret);
		$this->_arp_log($ret);
		
		$body = $this->_tj_html($controller, $request, 'emp/mac/tj_list_open');
		
		$this->_tj_mail($from, $bb, $subject, $body);
		
		echo "\n" . $_REQUEST['do'] . "\n";

		logdate($controller, $request);
		return true;
	}
	
	function _arp_log($a) {
		require_once(dirname(__FILE__) . '/../log/ArpLog.class.php');
		$aa = new ArpLog();
		
		$aa->_insert($a);
	}

	function z($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);

		$fmt = "UPDATE %s SET orderby = '%s' WHERE id = '%s'";
		while ($row = $db->fetch_array($result)) {
			$orderby = $this->xxx($row['ip']);
			$sql = sprintf($fmt, $this->tbl, $orderby, $row['id']);
			$db->query($sql);
		}

		$fmt = "UPDATE %s a, %s b SET a.emp = b.emp WHERE a.ip = b.ip";
		$sql = sprintf($fmt, Constant::tbl_ip, $this->tbl);
		$db->query($sql);

		echo "\n" . $_REQUEST['do'] . "\n";

		logdate($controller, $request);
		return true;
	}

	function xxx($ip) {
		$a = preg_split("/\\./i", $ip);

		return $a[3];
	}
	
	function alarm($ip, $fx, $bytes) {
		$kb = 1024;
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE ip = '%s'";
		$sql = sprintf($fmt, $this->tbl, $ip);
		// debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {			
			$speed = $this->_speed($fx, $row);
			$a = $speed * $kb * 60 * 5;
			
			if ($bytes > $a) {
				return false;
			}
		}

		return true;
	}
	
	function _speed($fx, $row) {
		if ($fx == '1') {
			$speed = $row['upload'];
			if (empty($speed) || $speed == 0) {
				$speed = 25;	 
			}
			
			return $speed;
		}
		
		if ($fx == '2') {
			$speed = $row['download'];
			if (empty($speed) || $speed == 0) {
				$speed = 200;
			}
			
			return $speed;
		}
		
		return 25;
	}
	
	function move($from, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE emp = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $from);
		debug($sql);
		$db->query($sql);
	}
	
	function ajax_ip($controller, $request) {
		$q = $request['q'];

		$data = $this->_ajax_ip($q);
		echo json_encode($data);
	}

	function _ajax_ip($q) {
		if (empty($q)) {
			debug("OK" . $q);
			return array();
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE ip LIKE '%s' ORDER BY ip";
		$sql = sprintf($fmt, $this->tbl, "%" . $q . "%");
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view($row['id']);
			
			$ret[] = $row;
		}

		return $ret;
	}
	
	function nat_ns($controller, $request) {
		$range = "192.168.16.0/22";
		$this->_shell_exec("/sbin/iptables -F jr-input\n");
		$this->_shell_exec("/sbin/iptables -F jr-output\n");
		
		require_once APP_LIB . 'IpAddr.class.php';
		$ipaddr = new IpAddr();
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE category in ('1', '3', '4')";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		$aa = array();	
		while ($row = $db->fetch_array($result)) {
			if (!$ipaddr->contains($range, $row['ip'])) {
				echo "S";
				continue;
			}
			
			$ip = $row['ip'];			
			
			$fmt = "/sbin/iptables -A jr-input -d %s -j ACCEPT\n";
			echo $cmd;
			$cmd = sprintf($fmt, $ip);
			$this->_shell_exec($cmd);
			
			// $fmt = "/sbin/iptables -A jr-output -s %s -j qq-output\n";
			$fmt = "/sbin/iptables -A jr-output -s %s -j ACCEPT\n";
			echo $cmd;
			$cmd = sprintf($fmt, $ip);
			$this->_shell_exec($cmd);
			
			$aa[] = $ip; 
		}

		return true;
	}
	
	function nat_sj($controller, $request) {
		$range = "192.168.0.0/21";
		$this->_shell_exec("/sbin/iptables -F jr-input\n");
		$this->_shell_exec("/sbin/iptables -F jr-output\n");
		$this->_shell_exec("/sbin/iptables -F mac-output\n");
		
		require_once APP_LIB . 'IpAddr.class.php';
		$ipaddr = new IpAddr();
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE category in ('1', '3', '4', '5') AND internet = '1'";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);	
		while ($row = $db->fetch_array($result)) {
			if (!$ipaddr->contains($range, $row['ip'])) {
				echo "S";
				continue;
			}
			
			$ip = $row['ip'];
			$mac = $row['mac'];			
			
			$fmt = "/sbin/iptables -A jr-input -d %s -j ACCEPT\n";	
			$cmd = sprintf($fmt, $ip);
			echo $cmd;
			$this->_shell_exec($cmd);
			
			// $fmt = "/sbin/iptables -A jr-output -s %s -j qq-output\n";
			// $fmt = "/sbin/iptables -A jr-output -s %s -j ACCEPT\n";
			$fmt = "/sbin/iptables -A jr-output -s %s -j mac-output\n";
			$cmd = sprintf($fmt, $ip);
			echo $cmd;
			$this->_shell_exec($cmd);
			
			$fmt = "/sbin/iptables -A mac-output -m mac --mac-source %s -j ACCEPT\n";
			$cmd = sprintf($fmt, $mac);
			echo $cmd;
			$this->_shell_exec($cmd);
		}
		
		$this->_shell_exec("/sbin/iptables -A jr-output -j DROP\n");
		$this->_shell_exec("/sbin/iptables -A mac-output -j DROP\n");

		return true;
	}
	
	function nat_qx($controller, $request) {
		$range = "192.168.8.0/22";
		$this->_shell_exec("/sbin/iptables -F jr-input\n");
		$this->_shell_exec("/sbin/iptables -F jr-output\n");
		$this->_shell_exec("/sbin/iptables -F mac-output\n");
	
		require_once APP_LIB . 'IpAddr.class.php';
		$ipaddr = new IpAddr();
	
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE category in ('1', '3', '4', '5') AND internet = '1'";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if (!$ipaddr->contains($range, $row['ip'])) {
				echo "S";
				continue;
			}
				
			$ip = $row['ip'];
			$mac = $row['mac'];
				
			$fmt = "/sbin/iptables -A jr-input -d %s -j ACCEPT\n";
			$cmd = sprintf($fmt, $ip);
			echo $cmd;
			$this->_shell_exec($cmd);
				
			// $fmt = "/sbin/iptables -A jr-output -s %s -j qq-output\n";
			// $fmt = "/sbin/iptables -A jr-output -s %s -j ACCEPT\n";
			$fmt = "/sbin/iptables -A jr-output -s %s -j mac-output\n";
			$cmd = sprintf($fmt, $ip);
			echo $cmd;
			$this->_shell_exec($cmd);
				
			$fmt = "/sbin/iptables -A mac-output -m mac --mac-source %s -j ACCEPT\n";
			$cmd = sprintf($fmt, $mac);
			echo $cmd;
			$this->_shell_exec($cmd);
		}
	
		// $this->_shell_exec("/sbin/iptables -A jr-output -j DROP\n");
		// $this->_shell_exec("/sbin/iptables -A mac-output -j DROP\n");
	
		return true;
	}
	
	function _list($list) {
		require_once APP_LIB . 'IpAddr.class.php';
		$ipaddr = new IpAddr();

		asort($list);

		$a = $list;
		$ret = array();
		while (list($k, $v) = each($list)) {
			if ($this->_contains($ipaddr, $a, $k)) {
				continue;
			}

			$ret[] = $v;
		}

		return $ret;
	}
	
	function _contains($ipaddr, $list, $ip) {
		reset($list);
		while (list($k, $v) = each($list)) {
			if ($k == $ip) {
				continue;
			}

			if ($ipaddr->contains($v, $ip)) {
				// echo sprintf("%s=%s\t%s\tS\n", $k, $v, $ip);
				return true;
			}
		}

		return false;
	}

	function _shell_exec($cmd) {
		echo $cmd;
		shell_exec($cmd);
	}
	
	function _exist_emp($emp) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE emp = '%s'";
		$sql = sprintf($fmt, $this->tbl, $emp);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return true;
		}
		
		return false;
	}
	
	function view_emp($controller, $request) {
		$this->pretreat($controller);
	
		$id = $request['id'];
	
		$ret = $this->_list_emp($id);
	
		$controller->assign_by_ref('result', $ret);
	
		$controller->display($request, 'emp/mac/_list');
		return true;
	}
}
?>
